
var express = require("express");
var router = express.Router();
const path = require('path');
const multer = require('multer');

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 确保这个文件夹已经存在

    },
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + Date.now() + ext)
    }
})

const upload = multer({ storage: storage });

// 路由处理上传
router.post('/upload', upload.single('file'), (req, res) => {
    const file = req.file;
    if (!file) {
        res.json({ code: 0, msg: 'No file uploaded' })
    }
    const fileUrl = `${req.protocol}://${req.get('host')}/uploads/${file.filename}`;
    // 将uploads文件夹设置为静态资源目录，方便通过浏览器访问其中的文件
    res.json({ code: 1, data: fileUrl });
});

module.exports = router;
